package update

import (
	"gitee.com/youbeiwuhuan/gin-practice/go-sqlx/model"
	"github.com/jmoiron/sqlx"
)

func createUser(db *sqlx.DB, user model.User) error {
	_, err := db.Exec(
		"INSERT INTO users (username, email) VALUES (?, ?)",
		user.UserName, user.Email,
	)
	return err
}
func updateUser(db *sqlx.DB, user model.User) error {
	_, err := db.Exec(
		"UPDATE users SET username=?, email=? WHERE id=?",
		user.UserName, user.Email, user.Id,
	)
	return err
}

func deleteUser(db *sqlx.DB, id int) error {
	_, err := db.Exec("DELETE FROM users WHERE id=?", id)
	return err
}

// 命名参数
func createUserNamed(db *sqlx.DB, user model.User) error {
	query := `INSERT INTO users (username, email) VALUES (:username, :email)`
	_, err := db.NamedExec(query, user)
	return err
}

// 事务
func transferMoney(db *sqlx.DB, fromID, toID int, amount float64) error {
	tx, err := db.Beginx()
	if err != nil {
		return err
	}

	defer func() {
		if err != nil {
			tx.Rollback()
		}
	}()

	// 从发送方账户扣款
	_, err = tx.Exec("UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, fromID)
	if err != nil {
		return err
	}

	// 向接收方账户转账
	_, err = tx.Exec("UPDATE accounts SET balance = balance + ? WHERE id = ?", amount, toID)
	if err != nil {
		return err
	}

	return tx.Commit()
}
